package scale

import (
	"math/rand"
	"sync"
)

func NewConfuseRule(seed int64, n int) (obj *ConfuseRule) {
	obj = &ConfuseRule{
		normalToConfuse: map[uint8]uint8{},
		confuseToNormal: map[uint8]uint8{},
	}

	arr := make([]string, n)
	for i := 0; i < n; i++ {
		arr[i] = tenToAny[i]
	}
	rander := rand.New(rand.NewSource(seed))
	for i := len(arr) - 1; i > 0; i-- {
		num := rander.Intn(i + 1)
		arr[i], arr[num] = arr[num], arr[i]
	}

	for i := 0; i < n; i++ {
		normal := tenToAny[i][0]
		confuse := arr[i][0]

		obj.mutex.Lock()
		obj.normalToConfuse[normal] = confuse
		obj.confuseToNormal[confuse] = normal
		obj.mutex.Unlock()
	}

	return
}

type ConfuseRule struct {
	normalToConfuse map[uint8]uint8
	confuseToNormal map[uint8]uint8
	mutex           sync.RWMutex
}

func (rule *ConfuseRule) NormalToConfuse(normal uint8) uint8 {
	rule.mutex.RLock()
	defer rule.mutex.RUnlock()
	return rule.normalToConfuse[normal]
}

func (rule *ConfuseRule) ConfuseToNormal(normal uint8) uint8 {
	rule.mutex.RLock()
	defer rule.mutex.RUnlock()
	return rule.confuseToNormal[normal]
}
